package com.me.forum.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.me.enums.RespType;
import com.me.forum.utils.components.model.IModel;
import com.me.forum.utils.components.model.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.io.PrintWriter;

/**
 * @description:
 * @author: Hao
 * @createtime: 2020/6/1 17:25:46
 */
@Configuration
public class SpringsecurityConfig extends WebSecurityConfigurerAdapter {
    private ObjectMapper mapper = new ObjectMapper();

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
	
    
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
                formLogin()
                .loginProcessingUrl("/login")
                .successHandler((request, response, authentication) -> {
                    IModel model = IModel.get();
	                model.add(RespType.User, request.getSession().getAttribute("user"));
                    model.success(true);
                    PrintWriter writer = response.getWriter();
                    mapper.writeValue(writer, model);
                    writer.flush();
                }).
                failureHandler((request, response, exception) -> {
					IModel model = IModel.get();
					model.success(false);
					PrintWriter writer = response.getWriter();
					mapper.writeValue(writer, model);
					writer.flush();
                }).


                and().
                logout().
                logoutUrl("/logout").
                logoutSuccessHandler((request, response, authentication) -> {
                    IModel model = IModel.get();
                    mapper.writeValue(response.getOutputStream(), model);
                }).

                and().
                authorizeRequests().
                anyRequest().permitAll().
	            // antMatchers("/admin/**").hasAuthority("root").
	            // anyRequest().authenticated().

                and().
                csrf().disable();

    }
}
